// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package purchase_list

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
)

// Logic
// 商品列表.
type Logic struct {
	arcade   *models.Arcades
	goods    *models.Goods
	request  *Request
	response []*Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: make([]*Response, 0),
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.arcade, _ = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err    error
		filter = map[string]any{
			"goods_id":  o.request.Id,
			"arcade_id": o.arcade.Id,
			"deleted":   kind.DeletedNo,
		}
		has   bool
		list  []*models.GoodsPurchase
		res   = result.New()
		total int64
	)

	// 1. 查询商品.
	if o.goods, has, err = services.NewGoodsService().Dao.GetById(ctx, o.request.Id); err != nil {
		// 1.1 数据错误.
		return res.WithError(errs.ErrDatabaseQuery)
	} else if !has || o.goods.ArcadeId != o.arcade.Id {
		// 1.2 商品不存在.
		return res.WithError(errs.ErrGoodsNotFound)
	}

	// 2. 查询过程.
	if list, total, err = services.NewGoodsPurchaseService().Paging(ctx, filter, o.request.Page, o.request.Size); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	} else {
		for _, item := range list {
			o.response = append(o.response, (&Response{}).With(item))
		}
	}

	// 3. 分页结果.
	return res.WithPaging(o.response, total, o.request.Page, o.request.Size)
}
